package cn.yuli.zookeeper.master;

import java.io.IOException;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;

import org.apache.log4j.Logger;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException.Code;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.AsyncCallback.DataCallback;
import org.apache.zookeeper.AsyncCallback.StringCallback;
import org.apache.zookeeper.data.Stat;

public class Master2 implements Watcher {
	
	private static Logger logger = Logger.getLogger(Master2.class);
	
	private static ZooKeeper zk;//zk客户端
	private String host;//地址
	private static String serverId = Integer.toHexString(new Random().nextInt());//产生服务id
	private static AtomicBoolean isLeader = new AtomicBoolean();
	private static CountDownLatch countDownLatch = new CountDownLatch(1);
	static StringCallback masterCreateCallback = new StringCallback() {
		
		public void processResult(int rc, String path, Object ctx, String name) {
			System.out.println("111111111111111111111111111111111111111111111");
			switch (Code.get(rc)) {
			case CONNECTIONLOSS:
				checkMaster();
				return;
			case OK:
				logger.info("成为主节点");
				isLeader.set(true);
				logger.info("方法里的"+isLeader);
			default:
				isLeader.set(false);
			}
			countDownLatch.countDown();
		}
	};
	static DataCallback masterCheckCallback = new DataCallback() {
		
		public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat) {
			switch (Code.get(rc)) {
			case CONNECTIONLOSS:
				checkMaster();
				return;
			case NONODE:
				runForMaster();
			default:
				break;
			}
			
		}
	};
	
	
	public Master2(String host) {
		this.host = host;
	}
	public void process(WatchedEvent event) {
		System.out.println(event);
	}
	
	
	public static void runForMaster() {
		zk.create("/master", serverId.getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL, masterCreateCallback, null);
	}
	
	public static void checkMaster() {
		zk.getData("/master", false,masterCheckCallback , null);
	}
	
	public void startZK() throws IOException{
		zk = new ZooKeeper(host, 15000, this);
	}
	public void stopZK() throws InterruptedException{
		zk.close();
	}
	
	
	public static void main(String[] args) throws IOException, InterruptedException {
		Master2 m = new Master2("39.108.170.73:2181");
		m.startZK();
		m.runForMaster();
		countDownLatch.await();
		logger.info("方法外的"+m.isLeader.get());
		if(m.isLeader.get()){
			logger.info("我已经成为了主节点");
			Thread.sleep(6000);
		}else{
			logger.info("有人已经成为了主节点");
		}
		m.stopZK();
	}
	

}
